<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '节目库',
  },
}
</route>

<script setup>
import BottomOperateBox from '@/components/BottomOperateBox.vue'
import ContentBox from '@/components/ContentBox.vue'
import CommonActivityItem from '@/components/CommonActivityItem.vue'
import { uniNavigateTo } from '@/utils'
import ProgrammeApi from '@/service/programme'
import ProgrammeItem from '@/components/ProgrammeItem.vue'
import { useSelectedProgrammeStore } from '@/store/selectedProgramme'
import { MAX_PROGRAMME_COUNT } from '@/configs/constant'
import BasePopup from '@/components/BasePopup.vue'
import {
  getAllTown,
  getDictDetail,
  dictMap,
  getProgrammeCategory,
} from '@/service/dict'

const {
  addSelectedProgramme,
  removeSelectedProgramme,
  setSelectedProgrammeList,
  clearSelectedProgrammeList,
} = useSelectedProgrammeStore()

const _selectedProgrammeList = computed(
  () => useSelectedProgrammeStore().selectedProgrammeList,
)

const _selectedProgrammeIdList = computed(() => {
  console.log('useSelectedProgrammeStore', useSelectedProgrammeStore())
  const sList = useSelectedProgrammeStore().selectedProgrammeList
  if (sList?.length) {
    return sList.map((item) => item.id)
  }
  return []
})

const toggleSelectItem = (item) => {
  if (_selectedProgrammeIdList.value.includes(item.id)) {
    removeSelectedProgramme(item)
  } else {
    if (_selectedProgrammeIdList.value.length >= MAX_PROGRAMME_COUNT) {
      uni.showToast({
        title: `最多选择${MAX_PROGRAMME_COUNT}个节目`,
        icon: 'none',
      })
      return
    }
    addSelectedProgramme(item)
  }
}

const selectedProgrammePopupVisible = ref(false)

const openSelectedProgrammePopup = () => {
  if (_selectedProgrammeIdList.value.length) {
    selectedProgrammePopupVisible.value = true
  } else {
    uni.showToast({
      title: '您还未选择任何节目',
      icon: 'none',
    })
  }
}

const isSelectedAll = computed(() => {
  const selectedList = _selectedProgrammeIdList.value.length
  return (
    selectedList === scrollState.dataList.length ||
    selectedList === MAX_PROGRAMME_COUNT
  )
})

const toggleSelectAll = () => {
  if (isSelectedAll.value) {
    clearSelectedProgrammeList()
  } else {
    // 设置 scrollState.dataList 的前 MAX_PROGRAMME_COUNT 个为选中
    setSelectedProgrammeList(scrollState.dataList.slice(0, MAX_PROGRAMME_COUNT))
  }
}

const handleNext = () => {
  uni.navigateBack()
}

/** ----------- 分页加载 start --------- */
const pageObj = ref({
  pageNo: 1,
  pageSize: 10,
})
const scrollState = reactive({
  refresherTriggered: false,
  dataList: [],
  loadState: 'loading',
})

const getDataList = async () => {
  if (scrollState.loadState === 'finished') return
  try {
    const params = {
      ...pageObj.value,
      column: 'createTime',
      order: 'desc',
      sysOrgCode: townState.currentValue,
      category: categoryState.currentValue || '',
    }
    const { code, result } = await ProgrammeApi.getProgrammePageNoLogin(params)
    if (code === 200 && result) {
      const { records, pages } = result
      if (records?.length) {
        scrollState.dataList = [...scrollState.dataList, ...records]
      }
      if (pageObj.value.pageNo < pages) {
        pageObj.value.pageNo++
      } else {
        scrollState.loadState = 'finished'
      }
    } else {
      scrollState.loadState = 'error'
    }
  } catch (e) {
    scrollState.loadState = 'error'
  }
}

const reset = () => {
  pageObj.value.pageNo = 1
  scrollState.dataList = []
  scrollState.loadState = 'loading'
}

const onRefresherrefresh = async () => {
  scrollState.refresherTriggered = true
  await refreshList()
  scrollState.refresherTriggered = false
}

const refreshList = async () => {
  try {
    uni.showLoading()
    reset()
    await getDataList()
  } finally {
    uni.hideLoading()
  }
}
/** ----------- 分页加载 end --------- */

/** ------------ 筛选项 start -------------- */
const townState = reactive({
  visible: false,
  currentValue: '',
  currentLabel: '',
  columns: [],
})
const getTownList = async () => {
  const { code, result } = await getAllTown()
  if (code === 200 && result) {
    townState.columns = [{ label: '全部镇(街)', value: '' }, ...result]
    const cItem = townState.columns[0]
    townState.currentValue = cItem.value
    townState.currentLabel = cItem.label
  }
}
const confirmTown = () => {
  const cItem = townState.columns.find(
    (item) => item.value === townState.currentValue,
  )
  if (cItem) {
    townState.currentLabel = cItem.label
  }
  refreshList()
  townState.visible = false
}

const categoryState = reactive({
  visible: false,
  currentValue: '',
  currentLabel: '',
  columns: [],
})
const getCategoryList = async () => {
  const { code, result } = await getProgrammeCategory()
  if (code === 200 && result) {
    categoryState.columns = result
    categoryState.currentValue = ''
    categoryState.currentLabel = '全部类型'
  }
}
const checkCategory = (child) => {
  if (child) {
    categoryState.currentValue = child.value
    categoryState.currentLabel = child.label
  } else {
    categoryState.currentValue = ''
    categoryState.currentLabel = '全部类型'
  }
  refreshList()
  categoryState.visible = false
}
/** ------------ 筛选项 end -------------- */

onMounted(async () => {
  await getTownList()
  await getCategoryList()
  refreshList()
})
</script>

<template>
  <view class="common-page-bg">
    <view class="p-24rpx">
      <!-- <FilterBar :filter-list="filterList" @change="handleChangeFilter" /> -->
      <view class="filter-bar">
        <view
          class="filter-bar-item"
          @click="townState.visible = true"
        >
          <view class="filter-bar-item-text">
            {{ townState.currentLabel }}
          </view>
          <view class="filter-bar-item-icon">
            <image
              class="h-32rpx w-32rpx"
              src="/static/icons/filter-arrow.png"
            />
          </view>
        </view>
        <view
          class="filter-bar-item"
          @click="categoryState.visible = true"
        >
          <view class="filter-bar-item-text">
            {{ categoryState.currentLabel }}
          </view>
          <view class="filter-bar-item-icon">
            <image
              class="h-32rpx w-32rpx"
              src="/static/icons/filter-arrow.png"
            />
          </view>
        </view>
      </view>
    </view>
    <scroll-view
      class="scroll-container"
      scroll-y
      refresher-enabled
      enable-back-to-top
      :refresher-triggered="scrollState.refresherTriggered"
      @refresherrefresh="onRefresherrefresh"
      @scrolltolower="getDataList"
    >
      <template v-if="scrollState.dataList.length">
        <view
          v-for="item in scrollState.dataList"
          :key="item.id"
          class="mb-24rpx flex items-center"
        >
          <view
            class="mr-24rpx"
            @click="toggleSelectItem(item)"
          >
            <image
              v-if="_selectedProgrammeIdList.includes(item.id)"
              class="w-32rpx h-32rpx"
              src="@/static/icons/check-active.png"
            ></image>
            <image
              v-else
              class="w-32rpx h-32rpx"
              src="@/static/icons/check-inactive.png"
            ></image>
          </view>
          <view class="px-32rpx rounded-16rpx bg-white flex-1">
            <CommonActivityItem
              :title="item.name"
              :img-src="item.coverUrl"
              :desc-list="[
                { label: '节目类型', value: item.category_dictText },
                { label: '节目时长', value: `${item.duration}分钟` },
              ]"
              @custom-click="
                uniNavigateTo('/pages-sub/programme/detail/index?id=' + item.id)
              "
            />
          </view>
        </view>
        <wd-loadmore
          finished-text="没有更多了"
          :state="scrollState.loadState"
          @reload="getDataList"
        />
      </template>
      <wd-status-tip
        v-else
        image="content"
        tip="暂无内容"
      />
    </scroll-view>
    <BottomOperateBox>
      <view class="flex items-center">
        <view class="flex items-center flex-shrink-0 w-300rpx">
          <template>
            <image
              v-if="_selectedProgrammeIdList.length"
              class="w-32rpx h-32rpx mr-16rpx"
              src="@/static/icons/check-active.png"
            ></image>
            <image
              v-else
              class="w-32rpx h-32rpx mr-16rpx"
              src="@/static/icons/check-inactive.png"
            ></image>
          </template>
          <view
            class="chose-all"
            @click="openSelectedProgrammePopup"
          >
            <text class="chose-all-active">已选</text>
            <text>
              （{{ _selectedProgrammeIdList.length }}/{{
                MAX_PROGRAMME_COUNT
              }}）
            </text>
          </view>
        </view>
        <wd-button
          custom-class="common-main-btn"
          @click="handleNext"
        >
          下一步
        </wd-button>
      </view>
    </BottomOperateBox>

    <!-- 乡镇弹窗 -->
    <BasePopup
      v-model:visible="townState.visible"
      title="请选择"
    >
      <template #headerRight>
        <wd-button
          type="text"
          @click="confirmTown"
        >
          确认
        </wd-button>
      </template>
      <wd-picker-view
        v-model="townState.currentValue"
        :columns="townState.columns"
      />
    </BasePopup>

    <!-- 类型弹窗 -->
    <BasePopup
      v-model:visible="categoryState.visible"
      title="请选择"
    >
      <view class="category-group">
        <view class="category-item">
          <view class="flex flex-wrap">
            <view
              class="category-item-child"
              :class="{ active: categoryState.currentValue === '' }"
              @click="checkCategory()"
            >
              全部类型
            </view>
          </view>
        </view>
        <view
          v-for="item in categoryState.columns"
          :key="item.value"
          class="category-item"
        >
          <view class="category-item-title">{{ item.label }}</view>
          <view
            v-if="item.children?.length"
            class="flex flex-wrap"
          >
            <view
              v-for="child in item.children"
              :key="child.value"
              class="category-item-child"
              :class="{ active: categoryState.currentValue === child.value }"
              @click="checkCategory(child)"
            >
              {{ child.label }}
            </view>
          </view>
        </view>
      </view>
    </BasePopup>

    <!-- 已选节目弹窗 -->
    <BasePopup
      v-model:visible="selectedProgrammePopupVisible"
      title="已选节目"
    >
      <view class="selected-programme-list">
        <view
          v-for="item in _selectedProgrammeList"
          :key="item.id"
          class="mb-24rpx flex items-center"
        >
          <view
            class="mr-24rpx"
            @click="toggleSelectItem(item)"
          >
            <image
              v-if="_selectedProgrammeIdList.includes(item.id)"
              class="w-32rpx h-32rpx"
              src="@/static/icons/check-active.png"
            ></image>
            <image
              v-else
              class="w-32rpx h-32rpx"
              src="@/static/icons/check-inactive.png"
            ></image>
          </view>
          <view class="px-32rpx rounded-16rpx bg-white flex-1">
            <CommonActivityItem
              :title="item.name"
              :img-src="item.coverUrl"
              :desc-list="[
                { label: '节目类型', value: item.category_dictText },
                { label: '节目时长', value: `${item.duration}分钟` },
              ]"
              @custom-click="
                uniNavigateTo('/pages-sub/programme/detail/index?id=' + item.id)
              "
            />
          </view>
        </view>
      </view>
    </BasePopup>
  </view>
</template>

<style lang="scss" scoped>
.common-page-bg {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.scroll-container {
  padding: 12rpx 24rpx 160rpx 24rpx;
  box-sizing: border-box;
}

.chose-all {
  font-size: 28rpx;
  color: $uni-text-color-grey;

  &-active {
    color: #f98f18;
  }
}

.filter-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-radius: 16rpx;

  &-item {
    position: relative;
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: center;
    height: 80rpx;

    &::after {
      position: absolute;
      top: 50%;
      right: 0;
      width: 1rpx;
      height: 32rpx;
      content: '';
      background-color: $uni-border-color;
      transform: translateY(-50%);
    }

    &:last-child {
      &::after {
        display: none;
      }
    }

    &-text {
      font-size: 28rpx;
      color: $uni-text-color;

      &.active {
        color: #f98f18;
      }
    }
  }
}

.category-group {
  padding: 32rpx;
  max-height: 50vh;
  overflow-y: auto;

  .category-item {
    margin-bottom: 16rpx;

    &-title {
      position: relative;
      padding-left: 24rpx;
      margin-bottom: 16rpx;
      font-size: 30rpx;
      font-weight: 500;
      color: $uni-text-color;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 8rpx;
        height: 32rpx;
        background-image: linear-gradient(169deg, #67bdf6 0%, #2c84db 100%);
        border-radius: 2rpx;
      }
    }

    &-child {
      min-width: 180rpx;
      padding: 12rpx;
      margin: 0 16rpx 16rpx 0;
      font-size: 26rpx;
      color: $uni-text-color-grey;
      text-align: center;
      background: #f4f7fc;
      box-sizing: border-box;
      border-radius: 8rpx;

      &.active {
        background: rgba(249, 143, 24, 0.2);
        color: #f98f18;
      }
    }
  }
}

.selected-programme-list {
  padding: 24rpx;
  max-height: 70vh;
  background: #f4f7fc;
  overflow-y: auto;
}
</style>
